package com.pkutech.carcasher.activity;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.text.InputType;
import android.text.TextUtils;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.TextView;

import com.afollestad.materialdialogs.MaterialDialog;
import com.dd.processbutton.iml.ActionProcessButton;
import com.pkutech.carcasher.R;
import com.pkutech.carcasher.bean.BaseResponse;
import com.pkutech.carcasher.model.HmSelectFormalOrder;
import com.pkutech.carcasher.network.SoapApi;
import com.pkutech.carcasher.utils.StringUtils;
import com.pkutech.carcasher.utils.ToastUtil;
import com.zsd.printer.PrinterCtrl;

import java.util.Arrays;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action0;
import rx.schedulers.Schedulers;

/**
 * Created by cyy on 2016/6/28.
 */
public class StopDetailActivity extends BaseActivity implements View.OnClickListener {

    @BindView(R.id.toolbar)
    Toolbar toolbar;
    @BindView(R.id.confirmBtn)
    ActionProcessButton confirmBtn;

    @BindView(R.id.in_printBtn)
    ActionProcessButton in_printBtn;

    String orderid = "";
    @BindView(R.id.text1)
    TextView text1;
    @BindView(R.id.text2)
    TextView text2;
    @BindView(R.id.text3)
    TextView text3;
    @BindView(R.id.text4)
    TextView text4;
    //    @BindView(R.id.text5)
//    TextView text5;
    @BindView(R.id.text6)
    TextView text6;
    @BindView(R.id.text7)
    TextView text7;

    HmSelectFormalOrder selectFormalOrder;
    @BindView(R.id.layout1)
    LinearLayout layout1;
    @BindView(R.id.layout2)
    LinearLayout layout2;
    @BindView(R.id.layout3)
    LinearLayout layout3;
    @BindView(R.id.layout4)
    LinearLayout layout4;
    @BindView(R.id.layout5)
    LinearLayout layout5;
    @BindView(R.id.layout6)
    LinearLayout layout6;
    @BindView(R.id.layout7)
    LinearLayout layout7;
    String ordercode;

    String carportcode;
    String carnum;
    String roadname;
    String stopStarttime;
    @BindView(R.id.carNumArrows)
    ImageView carNumArrows;
    @BindView(R.id.spinner1)
    Spinner spinner1;

    List<String> carTypeList;
    String carType = "0";

    @BindView(R.id.spinner2)
    Spinner spinner2;
    @BindView(R.id.spinner3)
    Spinner spinner3;
    @BindView(R.id.carNumText)
    EditText carNumText;

    List<String> provinceList;
    List<String> letterList;

    String curProvince;
    String curLetter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_stop_detail);
        ButterKnife.bind(this);
        initToolbar(toolbar);
        selectFormalOrder = (HmSelectFormalOrder) getIntent().getSerializableExtra(StopQueryActivity.STOPPER);
        //打印相关
        carportcode = selectFormalOrder.getCarportid();
        carnum = selectFormalOrder.getCarnum();
        roadname = selectFormalOrder.getRoadid();
        stopStarttime = selectFormalOrder.getStarttime();
        ordercode=selectFormalOrder.getCode();
        text1.setText(selectFormalOrder.getRoadid());
        text2.setText(selectFormalOrder.getCarportid());
        text3.setText(selectFormalOrder.getCarnum());
//        text8.setText(selectFormalOrder.getCarportid());
        text4.setText(selectFormalOrder.getStarttime());
//        text5.setText(selectFormalOrder.getCreatedate());
        if (!TextUtils.isEmpty(selectFormalOrder.getState()) && "1".equals(selectFormalOrder.getState())) {
            text6.setText("已结算");
        } else {
            text6.setText("未结算");
        }
        text7.setText(selectFormalOrder.getCreateuser());

        //如果地磁过来的  可以编辑车牌 车型 其他不可 1
        //如果直接补录  可以编辑所有的  2
        //如果预约过来的 只可以编辑车型  null
        if ("0".equals(selectFormalOrder.getCollectionstate())) {
            if ("3".equals(selectFormalOrder.getDifference())) {//
                layout5.setOnClickListener(this);//车型
                spinner1.setEnabled(true);
                spinner2.setEnabled(false);
                spinner3.setEnabled(false);
                carNumText.setEnabled(false);
            } else if ("1".equals(selectFormalOrder.getDifference())) {
                layout3.setOnClickListener(this);//车牌号
                layout5.setOnClickListener(this);//车型
                spinner1.setEnabled(true);
            } else {
                spinner1.setEnabled(false);
            }
        } else {
            spinner1.setEnabled(false);
            spinner2.setEnabled(false);
            spinner3.setEnabled(false);
            carNumText.setEnabled(false);
        }


        if ("1".equals(selectFormalOrder.getCollectionstate())) {
            confirmBtn.setVisibility(View.GONE);
            in_printBtn.setVisibility(View.VISIBLE);
        } else {
            confirmBtn.setVisibility(View.VISIBLE);
            in_printBtn.setVisibility(View.GONE);
        }
        String[] carTypes = getResources().getStringArray(R.array.car_type);
        carTypeList = Arrays.asList(carTypes);
        ArrayAdapter<String> adapter1 = new ArrayAdapter<String>(this, R.layout.park_name_spinner_item,
                R.id.text1, carTypeList);
        spinner1.setAdapter(adapter1);
        if (selectFormalOrder != null && !TextUtils.isEmpty(selectFormalOrder.getCarmodel())) {
            String carModel = selectFormalOrder.getCarmodel();
            if ("1".equals(carModel)) {
                carType = "1";
            } else if ("2".equals(carModel)) {
                carType = "2";
            } else if ("3".equals(carModel)) {
                carType = "3";
            } else {
                carType = "0";
            }
        }
        spinner1.setSelection(Integer.parseInt(carType));
        spinner1.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
//                String carTypeStr = carTypeList.get(position);
                carType = String.valueOf(position);
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });

        String carNum = selectFormalOrder.getCarnum();

        String[] provinces = getResources().getStringArray(R.array.provinces);
        provinceList = Arrays.asList(provinces);
        ArrayAdapter<String> adapter2 = new ArrayAdapter<String>(this, R.layout.park_name_spinner_item,
                R.id.text1, provinceList);
        spinner2.setAdapter(adapter2);

        int selectProvince = 0;
        if(!TextUtils.isEmpty(carNum) && carNum.length() > 0){
            String p = carNum.substring(0, 1);
            for(int i = 0; i < provinceList.size(); i++){
                if(p.equalsIgnoreCase(provinceList.get(i))){
                    selectProvince = i;
                }
            }
        }

        spinner2.setSelection(selectProvince);
        spinner2.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                curProvince = provinceList.get(position);
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });

        String[] letters = getResources().getStringArray(R.array.letters);
        letterList = Arrays.asList(letters);
        ArrayAdapter<String> adapter3 = new ArrayAdapter<String>(this, R.layout.park_name_spinner_item,
                R.id.text1, letterList);
        spinner3.setAdapter(adapter3);

        int selectLetter = 0;
        if(!TextUtils.isEmpty(carNum) && carNum.length() > 0){
            String l = carNum.substring(1, 2);
            for(int i = 0; i < letterList.size(); i++){
                if(l.equalsIgnoreCase(letterList.get(i))){
                    selectLetter = i;
                }
            }
        }

        spinner3.setSelection(selectLetter);
        spinner3.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                curLetter = letterList.get(position);
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });

        if(!TextUtils.isEmpty(carNum) && carNum.length() > 0){
            carNumText.setText(carNum.substring(2, carNum.length()));
        }
    }

    @OnClick(R.id.in_printBtn)
    public void printBtn(View view) {
        new Thread() {
            public void run() {
                String mynum=curProvince+curLetter+carNumText.getText();
                PrinterCtrl.powerOn();
                PrinterCtrl.PrintText("车牌号：" + mynum + "\n\n");
                PrinterCtrl.PrintText("停靠时间：" + text4.getText().toString() + "\n\n");
                PrinterCtrl.PrintText("车位号：" + text2.getText().toString() + "\n\n");
                PrinterCtrl.PrintText("路段号：" + text1.getText().toString() + "\n\n");
                try {
                    sleep(1000);
                } catch (InterruptedException e) {
                }

            }

            ;
        }.start();

    }

    @OnClick(R.id.confirmBtn)
    public void confirm() {
        String fullCarNum = "";
        if (!TextUtils.isEmpty(curProvince)) {
            fullCarNum += curProvince;
        }
        if (!TextUtils.isEmpty(curLetter)) {
            fullCarNum += curLetter;
        }
        if (!TextUtils.isEmpty(carNumText.getText())) {
            fullCarNum += carNumText.getText().toString();
        }
        if (TextUtils.isEmpty(carNumText.getText().toString())) {
            ToastUtil.showInfoToast(this, "请输入车牌号", ToastUtil.Position.TOP);
            return;
        } else if (!fullCarNum.matches("^[\\u4e00-\\u9fa5]{1}[a-zA-Z]{1}[a-zA-Z_0-9]{5}$")) {
            ToastUtil.showInfoToast(this, "请输入正确的车牌号", ToastUtil.Position.TOP);
            return;
        } else if ("0".equals(carType)) {
            ToastUtil.showInfoToast(this, "请选择车型", ToastUtil.Position.TOP);
            return;
        } else if (TextUtils.isEmpty(text2.getText().toString())) {
            ToastUtil.showInfoToast(this, "请输入车位号", ToastUtil.Position.TOP);
            return;
        }
        SoapApi.stopUpdate(curProvince+curLetter+carNumText.getText(), ordercode, carType)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .doOnSubscribe(new Action0() {
                    @Override
                    public void call() {
                        confirmBtn.setProgress(1);
                    }
                })
                .subscribe(new Subscriber<BaseResponse>() {
                    @Override
                    public void onCompleted() {
                        confirmBtn.setProgress(0);
                    }

                    @Override
                    public void onError(Throwable e) {
                        confirmBtn.setProgress(0);
                        ToastUtil.showInfoToast(StopDetailActivity.this, "停靠失败", ToastUtil.Position.TOP);
                    }

                    @Override
                    public void onNext(BaseResponse baseResponse) {
                        confirmBtn.setProgress(0);
                        if (baseResponse != null && !TextUtils.isEmpty(baseResponse.getStatus()) && "true".equals(baseResponse.getStatus())) {
                            ToastUtil.showSuccessToast(StopDetailActivity.this, "停靠成功", ToastUtil.Position.TOP);
                            confirmBtn.setVisibility(View.GONE);
                            in_printBtn.setVisibility(View.VISIBLE);
                            spinner1.setEnabled(false);
                            spinner2.setEnabled(false);
                            spinner3.setEnabled(false);
                            carNumText.setEnabled(false);
                        } else {
                            if (baseResponse != null && !TextUtils.isEmpty(baseResponse.getMessage())) {
                                ToastUtil.showInfoToast(StopDetailActivity.this, baseResponse.getMessage(), ToastUtil.Position.TOP);
                            } else {
                                ToastUtil.showInfoToast(StopDetailActivity.this, "停靠失败", ToastUtil.Position.TOP);
                            }
                        }
                    }
                });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.layout1:
                new MaterialDialog.Builder(this)
                        .title("停车场")
//                        .content(R.string.nick_name_label)
                        .inputType(InputType.TYPE_CLASS_TEXT)
                        .negativeText("取消")
                        .input("", text1.getText().toString(), new MaterialDialog.InputCallback() {
                            @Override
                            public void onInput(MaterialDialog dialog, CharSequence input) {
                                if (!TextUtils.isEmpty(input.toString().trim())) {
                                    text1.setText(input.toString());
                                }
                            }
                        }).show();
                break;
            case R.id.layout2:
                new MaterialDialog.Builder(this)
                        .title("订单号")
//                        .content(R.string.nick_name_label)
                        .inputType(InputType.TYPE_CLASS_TEXT)
                        .negativeText("取消")
                        .input("", text2.getText().toString(), new MaterialDialog.InputCallback() {
                            @Override
                            public void onInput(MaterialDialog dialog, CharSequence input) {
                                if (!TextUtils.isEmpty(input.toString().trim())) {
                                    text2.setText(input.toString());
                                }
                            }
                        }).show();
                break;
            case R.id.layout3:
                new MaterialDialog.Builder(this)
                        .title("车牌号")
//                        .content(R.string.nick_name_label)
                        .inputType(InputType.TYPE_CLASS_TEXT)
                        .negativeText("取消")
                        .input("", text3.getText().toString(), new MaterialDialog.InputCallback() {
                            @Override
                            public void onInput(MaterialDialog dialog, CharSequence input) {
                                if (!TextUtils.isEmpty(input.toString().trim())) {
                                    if (input.toString().matches("^[\\u4e00-\\u9fa5]{1}[a-zA-Z]{1}[a-zA-Z_0-9]{5}$")) {
                                        text3.setText(input);
                                    } else {
                                        ToastUtil.showErrorToast(StopDetailActivity.this, "请输入正确的车牌号", ToastUtil.Position.TOP);
                                    }
                                }
                            }
                        }).show();
                break;
            case R.id.layout4:
                new MaterialDialog.Builder(this)
                        .title("停车开始时间")
//                        .content(R.string.nick_name_label)
                        .inputType(InputType.TYPE_CLASS_TEXT)
                        .negativeText("取消")
                        .input("", text4.getText().toString(), new MaterialDialog.InputCallback() {
                            @Override
                            public void onInput(MaterialDialog dialog, CharSequence input) {
                                if (!TextUtils.isEmpty(input.toString().trim())) {
                                    text4.setText(input);
                                }
                            }
                        }).show();
                break;
//            case R.id.layout5:
//                new MaterialDialog.Builder(this)
//                        .title("订单创建时间")
////                        .content(R.string.nick_name_label)
//                        .inputType(InputType.TYPE_CLASS_TEXT)
//                        .negativeText("取消")
//                        .input("", text5.getText().toString(), new MaterialDialog.InputCallback() {
//                            @Override
//                            public void onInput(MaterialDialog dialog, CharSequence input) {
//                                if (!TextUtils.isEmpty(input.toString().trim())) {
//                                    text5.setText(input);
//                                }
//                            }
//                        }).show();
//                break;
            case R.id.layout6:
                new MaterialDialog.Builder(this)
                        .title("订单状态")
//                        .content(R.string.nick_name_label)
                        .inputType(InputType.TYPE_CLASS_TEXT)
                        .negativeText("取消")
                        .input("", text6.getText().toString(), new MaterialDialog.InputCallback() {
                            @Override
                            public void onInput(MaterialDialog dialog, CharSequence input) {
                                if (!TextUtils.isEmpty(input.toString().trim())) {
                                    text6.setText(input);
                                }
                            }
                        }).show();
                break;
            case R.id.layout7:
                new MaterialDialog.Builder(this)
                        .title("创建人")
//                        .content(R.string.nick_name_label)
                        .inputType(InputType.TYPE_CLASS_TEXT)
                        .negativeText("取消")
                        .input("", text7.getText().toString(), new MaterialDialog.InputCallback() {
                            @Override
                            public void onInput(MaterialDialog dialog, CharSequence input) {
                                if (!TextUtils.isEmpty(input.toString().trim())) {
                                    text7.setText(input);
                                }
                            }
                        }).show();
                break;
        }
    }

    protected void initToolbar(Toolbar toolbar){
        setSupportActionBar(toolbar);
        toolbar.setNavigationIcon(R.drawable.ic_arrow_back_white_24dp);
        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                setResult(Activity.RESULT_OK);
                finish();
            }
        });
    }

}
